package com.edoomath.api.handler.impl;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.http.annotation.Rao;
import com.demo2do.core.utils.CollectionUtils;
import com.edoomath.api.handler.TempFileHandler;
import com.edoomath.api.rao.TempFileRao;
import com.edoomath.api.utils.ZipFileUtils;
import com.edoomath.entity.course.CourseMaterail;

/**
 * 
 * @author mohanlan
 *
 */
@Component("autoLoginHandler")
public class TempFileHandlerImpl implements TempFileHandler {
	
	@Value("#{cloud['cloud.host']}")
    private String cloudHost;
	
	@Value("#{cloud['cloud.path']}")
    private String cloudPath;
	
	@Rao
	private TempFileRao tempFileRao;
	
	private static final Logger logger = LoggerFactory.getLogger(TempFileHandler.class);
	
	/*
	 * (non-Javadoc)
	 * @see com.edoomath.api.handler.TempFileHandler#generateTempFile(com.edoomath.entity.course.CourseMaterail)
	 */
	public String generateTempFile(CourseMaterail materail) {
		
		
		try {
			String fileHttpUrl = materail.getDownloadUrl();
			String filePath = StringUtils.replace(fileHttpUrl, cloudHost, cloudPath);
			filePath = URLDecoder.decode(filePath, "UTF-8");
			
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("filename", filePath);
			params.put("limit", 3);
			
			HttpResult result = tempFileRao.generateQrcode(params);
			
			if(!result.isValid()) {
				throw BusinessException.newInstance("500", result.getMessage());
			}
			
			return result.get("url").toString();
		} catch (UnsupportedEncodingException e) {
			throw BusinessException.newInstance("500", e.getMessage());
		}
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.edoomath.api.handler.TempFileHandler#generateTempFile(java.util.List)
	 */
	public String generateTempFile(List<CourseMaterail> materails) {
		
		try {
			String filePath = this.generateZipFilePath(materails);
			filePath = URLDecoder.decode(filePath, "UTF-8");
			
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("filename", filePath);
			params.put("limit", 3);
			
			HttpResult result = tempFileRao.generateQrcode(params);
			
			if(!result.isValid()) {
				throw BusinessException.newInstance("500", result.getMessage());
			}
			
			return result.get("url").toString();
		} catch (UnsupportedEncodingException e) {
			throw BusinessException.newInstance("500", e.getMessage());
		}
		
	}
	
	/**
	 * 
	 * @param materails
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	public String generateZipFile(List<CourseMaterail> materails) throws UnsupportedEncodingException {
		
		String filePath = this.generateZipFilePath(materails);
		
		String fileUrl = StringUtils.replace(filePath, cloudPath, cloudHost);
		
		return fileUrl;
	}
	
	/**
	 * 
	 * @param materails
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("unchecked")
	private String generateZipFilePath(List<CourseMaterail> materails) throws UnsupportedEncodingException {
		List<String> idsString = (List<String>) CollectionUtils.extractPropertyList(materails, "idString");
		String zipFileName = String.join("-", idsString) + ".zip";
		String filePath = cloudPath + "/" + zipFileName;
		File realFile = new File(filePath);
		if(!realFile.exists() || realFile.isDirectory()) {
			this.zipFiles(materails, filePath);
		}
		
		return filePath;
	}
	
	/**
	 * 
	 * @param materails
	 * @param zipName
	 * @throws UnsupportedEncodingException 
	 */
	@SuppressWarnings("unchecked")
	private void zipFiles(List<CourseMaterail> materails, String zipName) throws UnsupportedEncodingException {
		ZipFileUtils zipFileUtils = new ZipFileUtils(zipName);
		List<String> fileUrls = (List<String>) CollectionUtils.extractPropertyList(materails, "downloadUrl");
		
		List<String> filePaths = new ArrayList<String>();
		for(String fileUrl : fileUrls) {
			String filePath = StringUtils.replace(fileUrl, cloudHost, cloudPath);
			filePath = URLDecoder.decode(filePath, "UTF-8");
			logger.info("compress filepath is [{}]", filePath);
			filePaths.add(filePath);
		}
		zipFileUtils.compress(filePaths);
	}

}
